<?php

namespace app\api\controller;

use app\wechat\service\ExchangeService;
use think\admin\Controller;
use think\Exception;
use think\paginator\driver\Bootstrap;
use think\facade\Db;
use think\Validate;
use EasyWeChat\Factory;

//积分兑换前端控制器
class IntegralShopFront extends Controller
{
    private $notify_url = 'https://myr.wissun.net';
    private $end_start="2023-12-30 23:59:59"; //活动结束日期  
    private $erpdb="erpdb";//ERP数据库
    //明一宏业商户号
    private $myhy_options = [
            'app_id'  => 'wx504958290f5566b7',
            'secret'  => '145dc6351dde0a2ae610e8713a01e9a0',     // AppSecret
            'aes_key' => 'D0C1EAA33E71636574416DB12104F0EC',     // EncodingAESKey，安全模式与兼容模式下请一定要填写！！！
            'mch_id'  =>'1700134471',
            'key'     => 'D0C1EAA33E71636574416DB12104F0EC'
    ];
    
    
    //用户获取红包记录
    public function get_user_hongbao_log(){
        $user_id = input('user_id',"");
        $integral_goods = Db::name("winrecord")->where(['user_id' => $user_id,"is_delete"=>0])
        ->field("id,goods_name,integral,add_date,lottery_id,sncode,goods_no")
        ->order("id desc")
        ->select();
        foreach ($integral_goods as $kk=>$vv){
            $vv["add_date"]=date("Y-m-d H:i:s",$vv["add_date"]);
            if($vv["lottery_id"] ==44 ){
                $agin=Db::name("again_record")->where("order_status",1)->where("sn_code",$vv["sncode"])->find();
                if($agin){
                    $vv["is_duihuan"]=1;
                }else{
                    $vv["is_duihuan"]=0;
                }
            }
            $integral_goods[$kk]=$vv;
        }
        return xcx_success(['code' => 200, 'datalist' => $integral_goods]);
    }
    
    
    
    //用户获取积分记录
    public function get_user_integral_log2(){
        $user_id = input('user_id',"");
        $integral_goods = Db::name("integral_log")->where(['user_id' => $user_id])
        ->order("id desc")
        ->select();
        return xcx_success(['code' => 200, 'datalist' => $integral_goods]);
    }
    
    public function get_integral_shop_goods()
    {
        $type = input('typeid');
        $integral_goods = Db::name("IntegralShop")->where(['is_delete' => 0, 'status' => 1, 'exchange_type' => $type])
        ->field("id,pic,name,integral")->order("rank asc")->select();
        return xcx_success(['code' => 1, 'integral_goods' => $integral_goods]);
    }

    /** 积分商城中心 */
    public function integral_shop()
    {
        $user_id = input('user_id');
        $user = Db::name("users a")->join('wechat_userinfo b', 'a.user_id=b.user_id', 'left')->where(['a.user_id' => $user_id])
        ->field('a.user_id,a.integral,b.headimgurl')->find();
        $this->assign("user", $user);
        $integral_type = Db::name("exchange")->where(['is_delete' => 0, 'status' => 1])->field("id,name")->order("rank asc")->select();
        $integral_goods = [];
        if ($integral_type) {
            $integral_goods = Db::name("IntegralShop")->where(['is_delete' => 0, 'status' => 1, 'exchange_type' => $integral_type[0]["id"]])->field("id,pic,name,integral")->order("rank asc")->select();
        }
        $this->assign("integral_goods", $integral_goods);
        $this->assign("integral_type", $integral_type);
        $banner = Db::name("banner")->where(['is_delete' => 0])->field("id,pic,link")->order("id desc")->select();
        $this->assign("banner", $banner);
        return $this->fetch();
    }


    //积分商品兑换方法
    public function exchange_integral_goods()
    {
        $user_id = input('user_id');
        $goods_id = input('goods_id');
        $address_id = input('address_id');
        $a=strtotime($this->end_start);
        if(time() > $a){
            return xcx_error('活动已结束~');
        }
        if (!$user_id || !$goods_id) {
            return xcx_error('缺少必要参数');
        }
        $goods = Db::name("IntegralShop")->where(['id' => $goods_id, 'status' => 1])->find();
        if ($goods) {
            $user_info = Db::name("users")->where("user_id", $user_id)->field("integral")->find();
            if ($user_info["integral"] < $goods["integral"]) {
                return xcx_error('积分不足！');
            }
            if ($goods["stock"] < 1) {
                return xcx_error('库存不足！');
            }
            $address_info = Db::name('user_address')->where(['id'=>$address_id,'status'=>1])->find();
            if (!$address_info){
                return xcx_error('地址错误！');
            }
            try {
                //增加地址和用户匹配的判断
                if($address_info["user_id"] != $user_id){
                    return xcx_error('用户地址与提交地址不匹配，请检查之后再试！');
                }
                Db::startTrans();
                //新增一条兑换记录
                $add["add_time"] = time();
                $add["goods_name"] = $goods["name"];
                $add["integral"] = $goods["integral"];
                $add["user_id"] = $user_id;
                $add["username"] = $address_info["rec_user_name"];
                $add["mobile"] = $address_info["rec_mobile"];
                $add["address"] = $address_info['ad1'].$address_info['ad2'].$address_info['ad3'].$address_info['detail'];
                $add["address_id"] = $address_id;
                $ret = Db::name("exchange_record")->insert($add);

                //新增一条积分记录
                $user_integral = $user_info["integral"];
                $integral_log['source_type'] = 9;
                $integral_log['integral'] = $goods['integral'];
                $integral_log['user_id'] = $user_id;
                $integral_log['create_time'] = $add["add_time"];
                $integral_log['before_integral'] = $user_integral;
                $integral_log['after_integral'] = $user_integral - $goods['integral'];
                $res2 = Db::name('integral_log')->insert($integral_log);

                //减少用户积分
                $res = Db::name("users")->where(['user_id' => $user_id, 'integral' => ['>=', $goods["integral"]]])->setDec("integral", $goods["integral"]);
                if ($res && $res2 && $ret) {
                    Db::commit();
                    return xcx_success(['code' => 1, 'msg' => '兑换成功']);
                } else {
                    Db::rollback();
                    return xcx_error('兑换失败');
                }

            } catch (Exception $e) {
                Db::rollback();
                return xcx_error($e->getMessage());
            }
        } else {
            return xcx_error('未找到兑换商品');
        }
    }

	//获取预下订单信息
    public function confirm_order()
    {
        $request_data = input();
        $validate = new Validate([
            'user_id' => 'require|number',
            'goods_id' => 'require|number'
        ]);
        $check_res = $validate->check($request_data);
        if (!$check_res) {
            return xcx_error($validate->getError());
        }
        $user_info = Db::name('users')->where(['user_id' => $request_data['user_id']])->find();
        $goods_info = Db::name('beibi_shop')->where(['id' => $request_data['goods_id'], 'is_delete' => 0])->find();
        if(empty($user_info["address"])){
            $user_info["address"]="";
        }
        if(empty($user_info["rec_mobile"])){
            $user_info["rec_mobile"]="";
        }
        return xcx_success(['code' => 1, 'data' => ['user_info' => $user_info, 'goods_info' => $goods_info]]);
    }

    //获取预下订单信息
    public function confirm_order_integral()
    {
        $request_data = input();
        $validate = new Validate([
            'user_id' => 'require|number',
            'goods_id' => 'require|number'
        ]);
        $check_res = $validate->check($request_data);
        if (!$check_res) {
            return xcx_error($validate->getError());
        }
        $user_info = Db::name('wechat_userinfo')->where(['id' => $request_data['user_id']])->field("integral")->find();
        $goods_info = Db::name('goods_lists')->where(['id' => $request_data['goods_id'], 'status' => 1])->find();
        $goods_info["goods_pic"]=$this->notify_url.$goods_info["goods_pic"];
        return xcx_success(['code' => 200, 'data' => ['user_info' => $user_info, 'goods_info' => $goods_info]]);
    }

     //刷新支付参数-待支付订单再拉起支付
    public function reload_pay_json($log_id=0,$openid=""){
        $record_data=Db::name("exchange_record")->where("id",$log_id)->find();
        if($record_data){
            $user=Db::name("wechat_userinfo")->where("user_id",$record_data["user_id"])->field("routine_openid,openid")->find();
			if($openid){
				$user["routine_openid"]=$openid;
				Db::name("wechat_userinfo")->where("user_id",$record_data["user_id"])->update(["routine_openid"=>$openid]);
			}
            $app = new Application($this->myhy_options);
            $payment = $app->payment;
            $attributes = [
                'trade_type' => 'JSAPI',
                'body' => '金币商城兑换',
                'detail' => $record_data['goods_name'],
                'out_trade_no' => $record_data['order_no'],
                'total_fee' => $record_data['pay_price'] * 100,
                'notify_url' => $this->notify_url . '/api/integral_shop_front/wechat_pay_notify_myhy',
                'openid' => $user["routine_openid"],
                'attach' => ''
            ];
            
            $order = new Order($attributes);
            $result = $payment->prepare($order);
            if ($result->return_code == 'SUCCESS' && $result->result_code == 'SUCCESS') {
                $prepayId = $result->prepay_id;
                $json = $payment->configForPayment($prepayId);
                Db::name('exchange_record')->where(['id'=>$log_id])->update(['pay_json'=>$json]);
                return 1;
            }else{
                return 0;
            }
        }
    }

	 //经销商商城积分  积分兑换
    public function get_order_json_myhy()
    {
        $request_data = input('post.');
        $validate = new Validate([
            'user_id' => 'require|number',
            'goods_id' => 'require|number',
            'address_id'=>'require|number',
            'open_id'=>'require'
        ]);
        $check_res = $validate->check($request_data);
        if (!$check_res) {
            return xcx_success(['code'=>2,'msg'=>$validate->getError()]);
        }

        $address_info = Db::name('user_address')->where(['id'=>$request_data['address_id'],'status'=>1])->find();
        if (!$address_info){
            return xcx_error('地址错误！');
        }

        $goods_info = Db::name('goods_lists')->where(['id' => $request_data['goods_id'], 'status' => 1])->find();
        if (!$goods_info) {
            return xcx_success(['code'=>2,'msg'=>'未找到商品']);
        }
        if($goods_info["goods_type"] == 2){
            $user_code=$request_data["user_code"];
            $jxsinfo=Db::name("jxs_lists")->where("user_code",$user_code)->find();
            $exchange_log['dis_code'] = $user_code;
            $exchange_log['dis_name'] = $jxsinfo['nickname'];
            if ($jxsinfo['jxs_integral'] < $goods_info['integral']) {
                return xcx_success(['code'=>2,'msg'=>'积分不足']);
            }
        }else{
           return xcx_success(['code'=>2,'msg'=>'该商品不是经销商商品']);
        }
        if ($goods_info['stock'] <= 0) {  return xcx_success(['code'=>2,'msg'=>'库存不足']); }
        try {
            Db::startTrans();
            $before_integral=0;
            $out_trade_no = "my" . date("YmdHis") . "dh" . rand(0, 10000);
            //减少用户积分
            if($goods_info["goods_type"] == 2){
                $dec_user_integral_res = Db::name("jxs_lists")->where("user_code",$user_code)
                ->dec('jxs_integral', $goods_info['integral'])
                ->update();
                $before_integral=$jxsinfo['jxs_integral'];
                if (empty($goods_info['amount'])) {
                    $pp=Db::name('jxs_lists')->where('id',$jxsinfo["parent_id"])->value("jxs_integral");
                    Db::name('jxs_lists')->where('id',$jxsinfo["parent_id"])->inc('jxs_integral',$goods_info['integral'])->update();
                    //写入积分日志
                    $inlog["source_type"]=1;//增加
                    $inlog["integral"]=$goods_info['integral'];
                    $inlog["user_id"]=$jxsinfo['parent_id'];
                    $inlog["create_time"]=date("Y-m-d H:i:s");
                    $inlog["remark"]="下级兑换商品";
                    $inlog["after_integral"]=$pp+$goods_info['integral'];
                    $inlog["before_integral"]=$pp;
                    Db::name('integral_log')->insert($inlog);
                }
            }else{
                $dec_user_integral_res = Db::name('wechat_userinfo')->where(['id' => $request_data['user_id']])
                ->dec('integral', $goods_info['integral'])
                ->update();
            }
            //创建兑换记录
            if($goods_info["goods_type"] == 2){
                $exchange_log['order_type'] = 2;
            }
            $exchange_log['add_time'] =date('Y-m-d H:i:s');
            $exchange_log['goods_name'] = $goods_info['goods_name'];
            $exchange_log['integral'] = $goods_info['integral'];
            $exchange_log['user_id'] = $request_data['user_id'];
            $exchange_log['status'] = 0;
            $exchange_log['is_delete'] = 0;
            $exchange_log['order_no'] = $out_trade_no;
			$exchange_log['wx_mchid_order_no'] = $out_trade_no;
            $exchange_log['goods_no'] = $goods_info['id'];  //商品表id
            $exchange_log['pay_price'] = $goods_info['amount'];
            $exchange_log['goods_pic'] = $this->notify_url.$goods_info['goods_pic'];
            $exchange_log['nickname'] = $jxsinfo['nickname'];
            $exchange_log['username'] = $address_info['rec_user_name']; //姓名
            $exchange_log['mobile'] = $address_info['rec_mobile'];
            $exchange_log['address'] = $address_info['ad1'].$address_info['ad2'].$address_info['ad3'].$address_info['detail'];
            $exchange_log['address_id'] = $request_data['address_id'];
            $exchange_log['order_status'] = $goods_info['amount'] > 0 ? 0 : 1;    //需要付款则状态改为未付款，无需付款则改为已付款
            $inser_exchange_log_res = Db::name('exchange_record')->insertGetId($exchange_log);
            //减少商品库存
            $dec_goods_stock_res = Db::name('goods_lists')
            ->where(['id' => $request_data['goods_id']])
            ->where('stock', '>=', 1)->dec('stock', 1)
            ->update();
            
            //判断是否需要支付现金
            if ($goods_info['amount'] > 0) {
                //需要支付现金则调微信支付接口
                $open_id = $request_data["open_id"];
                $app = Factory::payment($this->myhy_options);
                $attributes = [
                    'trade_type' => 'JSAPI', // JSAPI，NATIVE，APP...
                    'body' => '积分商城兑换',
                    'detail' => $goods_info['goods_name'],
                    'out_trade_no' => $out_trade_no,
                    'total_fee' => $goods_info['amount'] * 100, // 单位：分
                    'notify_url' => $this->notify_url . '/api/integral_shop_front/wechat_pay_notify_myhy', 
                    'openid' => $open_id, 
                    'attach' => '' 
                ];
                $result = $app->order->unify($attributes);
                if ($result["return_code"] == 'SUCCESS' && $result["result_code"] == 'SUCCESS') {
                    $jssdk = $app->jssdk;
                    $prepayId = $result["prepay_id"];
                    $json = $jssdk->bridgeConfig($prepayId, false); // 返回数组
                    if ($inser_exchange_log_res && $dec_goods_stock_res) {
                        Db::name('exchange_record')->where(['id'=>$inser_exchange_log_res])->update(['pay_json'=>json_encode($json)]);
                        //写入积分日志
                        $inlog["source_type"]=2;//减少
                        $inlog["integral"]=$goods_info['integral'];
                        $inlog["user_id"]=$request_data['user_id'];
                        $inlog["create_time"]=date("Y-m-d H:i:s");
                        $inlog["remark"]="兑换商品";
                        $inlog["after_integral"]=$before_integral+$goods_info['integral'];
                        $inlog["before_integral"]=$before_integral;
                        Db::name('integral_log')->insert($inlog);
                        
                        Db::commit();
                        return xcx_success(['code' => 1, 'msg' => 'create json success', 'data' => $json]);
                    } else {
                        Db::rollback();
                        return xcx_success(['code' => 2, 'msg' => '支付订单创建失败~~']);
                    }
                } else {
                    Db::rollback();
                    return xcx_success(['code' => 2, 'msg' => $result["err_code_des"]]);
                }
            } else {
                //写入积分日志
                $inlog["source_type"]=2;//减少
                $inlog["integral"]=$goods_info['integral'];
                $inlog["user_id"]=$request_data['user_id'];
                $inlog["create_time"]=date("Y-m-d H:i:s");
                $inlog["remark"]="兑换商品";
                $inlog["after_integral"]=$before_integral+$goods_info['integral'];
                $inlog["before_integral"]=$before_integral;
                Db::name('integral_log')->insert($inlog);
                
                if ( $inser_exchange_log_res && $dec_goods_stock_res) {
                    Db::commit();
                    return xcx_success(['code' => 0, 'msg' => '兑换成功']);
                } else {
                    Db::rollback();
                    return xcx_success(['code' => 2, 'msg' => '兑换失败']);
                }
            }
        } catch (Exception $exception) {
            return xcx_success($exception->getMessage());
        }
    }


    //支付回调
    public function wechat_pay_notify_myhy()
    {
      
        $app = Factory::payment($this->myhy_options);
        $response = $app->handlePaidNotify(function($notify, $successful){
            file_put_contents('notify_log.txt',date("Y-m-d H:i:s").'=>'.json_encode($notify).PHP_EOL,FILE_APPEND);
            $order = Db::name('exchange_record')->where(['order_no' => $notify['out_trade_no']])->find();
            if (!$order) { // 如果订单不存在
                return 'Order not exist.'; // 告诉微信，我已经处理完了，订单没找到，别再通知我了
            }
            if ($order['order_status'] == 1) {
                return true; // 已经支付成功了就不再更新了
            }
            if ($successful) {
                // 不是已经支付状态则修改为已经支付状态
                Db::name('exchange_record')->where(['order_no' => $notify['out_trade_no'], 'order_status' => 0])->update([
                    'order_status' => 1, 
                    'update_time' => date('Y-m-d H:i:s'),
                    'pay_time'=>time(),
                    'notify'=>json_encode($notify)
                ]);
                $parent_id=Db::name("jxs_lists")->where('user_code',$order["dis_code"])->value("parent_id");
                $pp=Db::name("jxs_lists")->where('id',$parent_id)->value("jxs_integral");
                Db::name('jxs_lists')->where('id',$parent_id)->inc('jxs_integral',$order['integral'])->update();
                 //写入积分日志
                $inlog["source_type"]=1;//增加
                $inlog["integral"]=$order['integral'];
                $inlog["user_id"]=$parent_id;
                $inlog["create_time"]=date("Y-m-d H:i:s");
                $inlog["remark"]="下级兑换商品";
                $inlog["after_integral"]=$pp+$order['integral'];
                $inlog["before_integral"]=$pp;
                Db::name('integral_log')->insert($inlog);
            }
            return true; // 返回处理完成
        });

        return $response;
    }
    
    //根据分类获取商品列表
    public function get_goods_list_by_typeid()
    {
        $type_id = input("type_id");
        $page_num = input('page_num',1);
        $page_size = input('page_size',10);

        $validate = new Validate([
            'type_id'=>'require|number',
            'page_num'=>'require|number|>=:1'
        ]);
        $check_res = $validate->check(['type_id'=>$type_id,'page_num'=>$page_num]);
        if (!$check_res){
            return xcx_error($validate->getError());
        }else{
            $integral_goods = Db::name("integral_shop")->where(['is_delete'=>0,'status'=>1,'exchange_type'=>$type_id])
            ->limit(($page_num-1)*$page_size,$page_size)->field("id,pic,pics,name,integral,amount,stock,exchange_type")->order("rank asc")
            ->select();
            foreach($integral_goods as $k=>$val){
                if($val["pics"]){
                    $val["pics"]=explode("|",$val["pics"]);
                    if($val["pic"]){
                        array_push($val["pics"],$val["pic"]);
                    }
                }else{
                    $val["pics"]=[];
                    if($val["pic"]){
                        array_push($val["pics"],$val["pic"]);
                    }
                }
                $integral_goods[$k]=$val;
            }
            return xcx_success(['code'=>1,'integral_goods'=>$integral_goods]);
        }
    }

    //商品列表
    public function get_beibi_goods_list()
    {
            $uid = input("uid");
            $page_num = input('page_num',1);
            $page_size = input('page_size',10);
            $validate = new Validate([
                'page_num'=>'require|number|>=:1'
            ]);
            $check_res = $validate->check(['page_num'=>$page_num]);
            if (!$check_res){
                return xcx_error($validate->getError());
            }else{
                $integral_goods = Db::name("goods_lists")->where(['status'=>1,'goods_type'=>1])
                    ->where("status",1)
                    ->limit($page_size)
                    ->page($page_num)
                    ->order("id asc")
                    ->select();
                
                foreach($integral_goods as $k=>$val){
                    $val["goods_pic"]=$this->notify_url.$val["goods_pic"];
                    $integral_goods[$k]=$val;
                }
                return xcx_success(['code'=>1,'integral_goods'=>$integral_goods]);
            }
    }
    
    //经销商商品列表
    public function get_jxs_goods_list()
    {
        $uid = input("uid");
        $user_code=input("user_code","");
        $page_num = input('page_num',1);
        $page_size = input('page_size',10);
        $validate = new Validate([
            'page_num'=>'require|number|>=:1'
        ]);
        $check_res = $validate->check(['page_num'=>$page_num]);
        if (!$check_res){
            return xcx_error($validate->getError());
        }else{
            $jxs_integral=Db::name("jxs_lists")->where("user_code",$user_code)->value("jxs_integral");
            $integral_goods = Db::name("goods_lists")->where(['status'=>1,'goods_type'=>2])
                ->where("status",1)
                ->limit($page_size)
                ->page($page_num)
                ->order("id asc")
                ->select();
            
            foreach($integral_goods as $k=>$val){
                $val["goods_pic"]=$this->notify_url.$val["goods_pic"];
                $integral_goods[$k]=$val;
            }
            return xcx_success(['code'=>1,'integral_goods'=>$integral_goods,"jxs_integral"=>$jxs_integral]);
        }
    }
    
    //获取分类
    public function get_goods_type_list(){
        $type_list = Db::name("exchange")->where(['is_delete'=>0,'status'=>1])->order("rank asc")->select();
        return xcx_success(['code'=>1,'type_list'=>$type_list]);
    }

    //获取banner_url
    public function get_banner_list_integreal(){
        $user_id = input('user_id');
        $banner=Db::name("banner")->where("is_delete",0)->field("id,pic,link")->order("id desc")->select();
        $user_integral = Db::name('users')->where('user_id',$user_id)->value('integral');
        if (empty($user_integral)){
            $user_integral = 0;
        }
        $user_integral=0;
        return xcx_success(['code'=>1,'banner_list'=>$banner,'integral'=>$user_integral]);
    }
    
    //根据罐底码获取产品信息
    public function vcode_sncode(){
        $sncode=input("sncode","");
        $erpdb=Db::connect($this->erpdb);
        $vcode=$erpdb->table("v_code")->where("TrackCode='".$sncode."'")->find();
        //亲然品项
        if(in_array($vcode["ProductCD"],["1110393","1110394","1110395"])){
            $goodslist=Db::name("scan_product_config")->where("product_code","in",["1110393","1110394","1110395"])
            ->order("product_code asc")->select();
            
        }else if(in_array($vcode["ProductCD"],["1110409","1110410","1110411"])){
            //优煦
            $goodslist=Db::name("scan_product_config")->where("product_code","in",["1110409","1110410","1110411"])
            ->order("product_code asc")->select();
            
        }else if(in_array($vcode["ProductCD"],["1110180","1110181","1110182"])){
            //牧羊纯
            $goodslist=Db::name("scan_product_config")->where("product_code","in",["1110180","1110181","1110182"])
            ->order("product_code asc")->select();
        }         
        return xcx_success(['code'=>1,'data'=>$vcode,"goodslist"=>$goodslist]);
    }

    //获取banner_url
    public function get_banner_list(){
        $user_id = input('user_id');
        $banner=Db::name("banner")->where("is_delete",0)->field("id,pic,link")->order("id desc")->select();
        $user_integral = Db::name('users')->where('user_id',$user_id)->value('beibi');
        if (empty($user_integral)){
            $user_integral = 0;
        }
        $user_integral2 = Db::name('users')->where('user_id',$user_id)->value('integral');
        if (empty($user_integral2)){
            $user_integral2 = 0;
        }
        return xcx_success(['code'=>1,'banner_list'=>$banner,'integral'=>$user_integral,"integral2"=>$user_integral2]);
    }

    //获取兑换记录
    public function get_user_exchange_log()
    {
        $user_id=input('user_id');
        $page = input('page',1);
        $page_size = input('page_size',10);
		$openid=input('openid',"");
        $record=Db::name("exchange_record")->where("user_id",$user_id)->limit($page_size)->page($page)
        ->where("order_type",1)
        ->field("id,add_time,goods_pic,integral,nickname,username,order_no,pay_price,mobile,order_status,status,goods_name,address")
        ->order("id","desc")->select();
        foreach ($record as $kk=>$value){
            $date_arr=explode(" ",$value["add_time"]);
            $value["date"]=$date_arr[0];
            $value["time"]=$date_arr[1];
            switch ($value["order_status"]){
                case 0:
                    $value["status_txt"]="待支付";
                    if(empty($value["pay_json"])){
                        //$this->reload_pay_json($value["id"],$openid);
                    }
                    break;
                case 1:
					$value["status_txt"] = $value["status"] == 1?'已发放':'待发放';
                    
                    break;
                case 2:
                    $value["status_txt"]="已退款退积分";
                    break;
                case 3:
                    $value["status_txt"]="退款中";
                    break;
                case 4:
                    $value["status_txt"]="已关闭,积分已返还";
                    break;
                default:
                    $value["status_txt"]="未知";
            }
            $record[$kk]=$value;
            
        }
        return xcx_success(['code'=>1,'data'=>$record]);
    }

    //获取经销商兑换记录
    public function get_jxs_exchange_log()
    {
        $user_id=input('user_id');
        $page = input('page',1);
        $page_size = input('page_size',10);
		$openid=input('openid',"");
        $record=Db::name("exchange_record")->where("user_id",$user_id)->limit($page_size)->page($page)
        ->where("order_type",2)
        ->field("id,add_time,goods_pic,integral,nickname,username,order_no,pay_price,mobile,order_status,status,goods_name,address,courier_code,logistics_company,complate")
        ->order("id","desc")->select();
        foreach ($record as $kk=>$value){
            $date_arr=explode(" ",$value["add_time"]);
            $value["date"]=$date_arr[0];
            $value["time"]=$date_arr[1];
            switch ($value["order_status"]){
                case 0:
                    $value["status_txt"]="待支付";
                    if(empty($value["pay_json"])){
                        $this->reload_pay_json($value["id"],$openid);
                    }
                    break;
                case 1:
					$value["status_txt"] = $value["status"] == 1?'已发放':'待发放';
                    if($value["complate"]){
					    $value["status_txt"] ="已收货";
					}
                    break;
                case 2:
                    $value["status_txt"]="已退款退积分";
                    break;
                case 3:
                    $value["status_txt"]="退款中";
                    break;
                case 4:
                    $value["status_txt"]="已关闭,积分已返还";
                    break;
                default:
                    $value["status_txt"]="未知";
            }
            $record[$kk]=$value;
        }
        return xcx_success(['code'=>1,'data'=>$record]);
    }
    
    //获取经销商兑换记录-下级兑换订单
    public function get_jxs_exchange_log2()
    {
        $user_id=input('user_id');
        $page = input('page',1);
        $page_size = input('page_size',10);
		$openid=input('openid',"");
		$fid=input("fid","");
		$child_user_code=Db::name("jxs_lists")->where("parent_id",$fid)->column("user_code");
	
        $record=Db::name("exchange_record")
        ->where("dis_code","in",$child_user_code)
        ->limit($page_size)->page($page)
        ->where("order_type",2)
        ->where("order_status",1)
        ->field("id,add_time,goods_pic,integral,nickname,username,order_no,pay_price,mobile,order_status,status,goods_name,address,courier_code,logistics_company")
        ->order("id","desc")
        ->select();
        foreach ($record as $kk=>$value){
            $date_arr=explode(" ",$value["add_time"]);
            $value["date"]=$date_arr[0];
            $value["time"]=$date_arr[1];
            switch ($value["order_status"]){
                case 0:
                    $value["status_txt"]="待支付";
                    if(empty($value["pay_json"])){
                        $this->reload_pay_json($value["id"],$openid);
                    }
                    break;
                case 1:
					$value["status_txt"] = $value["status"] == 1?'已发放':'待发放';
				
                    break;
                case 2:
                    $value["status_txt"]="已退款退积分";
                    break;
                case 3:
                    $value["status_txt"]="退款中";
                    break;
                case 4:
                    $value["status_txt"]="已关闭,积分已返还";
                    break;
                default:
                    $value["status_txt"]="未知";
            }
            $record[$kk]=$value;
        }
        return xcx_success(['code'=>1,'data'=>$record]);
    }
    
   
     //获取再来一罐兑换记录
    public function get_user_exchange_log3()
    {
        $user_id=input('user_id');
        // $user_id=29;
        $page = input('page',1);
        $page_size = input('page_size',10);
		$openid=input('openid',"");
        $record=Db::name("again_record")->where("user_id",$user_id)->limit($page_size)->page($page)
        ->order("id","desc")->select();
        foreach ($record as $kk=>$value){
            $date_arr=explode(" ",$value["add_time"]);
            $value["date"]=$date_arr[0];
            $value["time"]=$date_arr[1];
            switch ($value["order_status"]){
                case 0:
                    $value["status_txt"]="待支付";
                    if(empty($value["pay_json"])){
                        //$this->reload_pay_json($value["id"],$openid);
                    }
                    break;
                case 1:
					$value["status_txt"] = $value["status"] == 1?'已发放':'待发放';
                    
                    break;
                case 2:
                    $value["status_txt"]="已退款退积分";
                    break;
                case 3:
                    $value["status_txt"]="退款中";
                    break;
                case 4:
                    $value["status_txt"]="已关闭,积分已返还";
                    break;
                default:
                    $value["status_txt"]="未知";
            }
            $record[$kk]=$value;
            
        }
        return xcx_success(['code'=>1,'data'=>$record]);
    }

   
  //获取再来一罐兑换记录
    public function get_user_again_log2()
    {
          $user_id=input('user_id');
          $page = input('page',1);
          $page_size = input('page_size',10);
          $openid=input('openid',"");
          $record=Db::name("again_record")->where("user_id",$user_id)
          ->where("order_status",1)->limit(($page-1)*$page_size.','.$page_size)->order("id","desc")->select();
          foreach ($record as &$value){
              $date_arr=explode(" ",$value["add_time"]);
              $value["date"]=$date_arr[0];
              $value["time"]=$date_arr[1];
              $value["pay_time"]=date("Y-m-d H:i:s",$value["pay_time"]);
              $value["goods_pic"]="";
              switch ($value["order_status"]){
                  case 0:
                      $value["status_txt"]="待支付";
                      break;
                  case 1:
                      if($value["dh_way"]){
                          $value["status_txt"] = "线下兑换";
                      }else{
                          $value["status_txt"] = $value["status"] == 1?'已发放':'待发放';
                      }
                      break;
                  case 2:
                      $value["status_txt"]="已退款";
                      break;
                  case 3:
                      $value["status_txt"]="退款中";
                      break;
                  case 4:
                      $value["status_txt"]="已关闭";
                      break;
                  default:
                      $value["status_txt"]="未知";
              }
          }
          return xcx_success(['code'=>1,'data'=>$record]);
    }   
    
    //获取积分核销码记录
    public function integral_hx_log(){
          $user_id=input('user_id');
          $page = input('page',1);
          $page_size = input('page_size',10);
          $openid=input('openid',"");
          $record=Db::name("intregral_order_hx")
          ->where("user_id",$user_id)
          ->limit(($page-1)*$page_size.','.$page_size)
          ->order("id","desc")
          ->select();
          foreach ($record as &$value){
              if($value["hx_status"] == 0 && $value["status"]==1){
                  $value["status_txt"]="待核销";
                  $a=time()-strtotime($value["hx_shenchen_time"]);
                  if($a > 1800){
                    $ff=true;$hx_code="";
                    $chars_array = array(
        			    "A", "B", "C", "D", "E", "F", "G",
        			    "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R",
        			    "S", "T", "U", "V", "W", "X", "Y", "Z"
        			);
                    while($ff){
                        $z=mt_rand(0,25);
                        $zd=$chars_array[$z];
                        $hx_code=$zd.mt_rand(10000000,99999999);
                        $isce=Db::name("intregral_order_hx")->where("hx_code",$hx_code)->count();
                        if(empty($isce)){ $ff=false;}
                    }
                    $value["hx_code"]=$hx_code;//核销码生成规则
                    $value["hx_shenchen_time"]=date("Y-m-d H:i:s");
                  }
              }else if($value["hx_status"] == 1 && $value["status"]==1){
                  $value["status_txt"]="已核销";
              }else if($value["status"]==2){
                  $value["status_txt"]="已取消";
              }
              
          }
          return xcx_success(['code'=>1,'data'=>$record]);
    }

    //获取用户积分记录
    public function get_user_integral_log()
    {
        $user_id=input('user_id');
        $page = input('page',1);
        $page_size = input('page_size',10);

        $integral_log=Db::name("integral_log a")
        ->join('integral_source_type b','a.source_type=b.id','left')
        ->where("a.user_id",$user_id)->limit(($page-1)*$page_size.','.$page_size)
        ->where("a.create_time",">=","2024-01-01")
        ->order("a.id","desc")
        ->field('a.*,b.title as source_type_title')
        ->select();
        foreach ($integral_log as &$value){
            $date_arr=explode(" ",$value["create_time"]);
            $value["date"]=$date_arr[0];
            $value["time"]=$date_arr[1];
        }

        return xcx_success(['code'=>1,'data'=>$integral_log]);
    }


	//根据物流单号获取兑换订单号
	public function wuliu_order(){
	    $wuliu=input("wuliu","");
	    if($wuliu){
	        $map["order_status"]=1;
	        $map["courier_code"]=$wuliu;
	        $result=Db::name("beibi_exchange_record")->where($map)->select();
	        if($result){
	            if($result[0]["send_sn_code"]){
	                return xcx_success(['code'=>0,'data'=>"该订单已上传信息，请勿重复上传"]);
	            }
	            $order["order_no"]=$result[0]["order_no"];
	            $order["status"]=$result[0]["status"];
	            $order["mobile"]=$result[0]["mobile"];
	            $order["username"]=$result[0]["username"];
	            $order["address"]=$result[0]["address"];
	            $order["courier_code"]=$result[0]["courier_code"];
	            $order["logistics_company"]=$result[0]["logistics_company"];
	            $detail=[];
	            foreach ($result as $k=>$val){
	                $ar["goods_name"]=$val["goods_name"];
	                $ar["id"]=$val["id"];
	                array_push($detail,$ar);
	            }
	            return xcx_success(['code'=>1,'data'=>$detail,"order"=>$order]);
	        }
	    }
	    return xcx_success(['code'=>0,'data'=>"没有找到订单信息"]);
	}
	
	//填入订单号与罐底码信息
	public function sumbit_order_sncode(){
	    $wuliu=input("wuliu","");
	    $sncode=input("sncode","");
	    if($wuliu){
	        $sncode=json_decode($sncode,true);
	        foreach ($sncode as $k=>$val){
	            $map["order_status"]=1;
	            $map["id"]=$val["id"];
	            $result=Db::name("beibi_exchange_record")->where($map)->find();
	            if($result){
	                if($result["send_sn_code"]){
	                    continue;
	                }else{
	                    $update["send_sn_code"]=$val["sncode"];
	                    Db::name("beibi_exchange_record")->where($map)->update($update);
	                }
	            }
	        }
	        return xcx_success(['code'=>1,'data'=>"提交成功"]);
	    }
	    return xcx_success(['code'=>0,'data'=>"没有找到订单信息"]);
	}
	
	//获取牧兰纯产品信息
	public function confirm_order_myc(){
	    $id=input("id","");
	    $order=Db::name("myc_onebyone_order")->where("id",$id)->find();
	    return xcx_success(['code'=>1,"order"=>$order]);
	}
	
	//拉起支付订单
	public function get_order_json_myc_myhy(){
	    $request_data = input('post.');
         $validate = new Validate([
             'user_id' => 'require|number',
             'id' => 'require|number',
             'address_id'=>'require|number',
             'open_id'=>'require'
         ]);
         $check_res = $validate->check($request_data);
         if (!$check_res) {
             return xcx_success(['code'=>2,'msg'=>$validate->getError()]);
         }
         $user_info = Db::name('users')->where(['user_id' => $request_data['user_id']])->find();
         if (!$user_info) {
             return xcx_success(['code'=>2,'msg'=>'未找到用户']);
         }
         
         $goods_info = Db::name('myc_onebyone_order')->where(['id' => $request_data['id']])->find();
         if (!$goods_info) {
             return xcx_success(['code'=>2,'msg'=>'未找到订单']);
         }
         
         if($goods_info["status"] != 1){
            return xcx_error('订单状态不符合规则！'.$goods_info["status"]);
         }
         
         $address_info = Db::name('user_address')->where(['id'=>$request_data['address_id'],'status'=>1])->find();
         if (!$address_info){
             return xcx_error('地址错误！');
         }
         
         try {
             $out_trade_no = "MYC" . date("YmdHis") . "" . rand(0, 10000);
             //判断是否需要支付现金
             if ($goods_info['amount'] > 0) {
                 //需要支付现金则调微信支付接口
                 $open_id = $request_data["open_id"];
                 $app = new Application($this->myhy_options);
                 $payment = $app->payment;
                 $attributes = [
                     'trade_type' => 'JSAPI', 
                     'body' => '牧兰纯一送一',
                     'detail' => $goods_info['product_name'],
                     'out_trade_no' => $out_trade_no,
                     'total_fee' => $goods_info['amount'] * 100, // 单位：分
                     'notify_url' => $this->notify_url . '/wechat/integral_shop_front/wechat_pay_notify_myc_myhy', // 支付结果通知网址，如果不设置则会使用配置里的默认地址
                     'openid' => $open_id,
                     'attach' => '' 
                 ];
                 $order = new Order($attributes);
                 $result = $payment->prepare($order);
                 if ($result->return_code == 'SUCCESS' && $result->result_code == 'SUCCESS') {
                     $prepayId = $result->prepay_id;
                     $json = $payment->configForPayment($prepayId);
                     if ($json) {
                         Db::commit();
                         $goods_info = Db::name('myc_onebyone_order')->where(['id' => $request_data['id']])->update(["order_no"=>$out_trade_no,'address_id'=>$address_info["id"]]);
                         return xcx_success(['code' => 1, 'msg' => 'create json success', 'data' => $json]);
                     } else {
                         Db::rollback();
                         return xcx_success(['code' => 2, 'msg' => '支付订单创建失败~~']);
                     }
                 } else {
                     Db::rollback();
                     return xcx_success(['code' => 2, 'msg' => $result->err_code_des]);
                 }
             }
         } catch (Exception $exception) {
             return xcx_success($exception->getMessage());
         }
	}
	
	//牧兰纯一送一支付回调
    public function wechat_pay_notify_myc_myhy()
    {
        $app = new Application($this->myhy_options);
        $response = $app->payment->handleNotify(function ($notify, $successful) {
            file_put_contents('myhy_notify_log.txt',date("Y-m-d H:i:s").'=>'.json_encode($notify).PHP_EOL,FILE_APPEND); 
            $order = Db::name('myc_onebyone_order')->where(['order_no' => $notify['out_trade_no']])->find();
            if (!$order) {  return 'Order not exist.';   }
            if ($order['status'] == 2) {  return true;  }
            if ($successful) {
                // 不是已经支付状态则修改为已经支付状态
                Db::name('myc_onebyone_order')->where(['order_no' => $notify['out_trade_no']])->update([
                    'status' => 2,
                    'pay_time'=>time()
                ]);
                //抛送聚水潭
                file_curl_v4('https://ayh.wissun.net/api/jushuitan/score_beibi_exchange_order_to_jushuitan3?exchange_record_id='.$order['id']);
                
            }
            return true; 
        });
        return $response;
    }
	
}